<?php

namespace App\Repositories\Manage;

use App\Models\DailyMenu;
use App\Models\MenuProductMapping;
use Illuminate\Support\Facades\DB;

class DailyMenuRepository
{

    public function getList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $res = (new DailyMenu())->setTable("dm")
            ->from("daily_menu as dm")
            ->join("supplier as s", "s.id", "dm.shop_id")
            ->when(!empty($filter['shop_id']), function ($query) use ($filter) {
                return $query->where("s.id", $filter['shop_id']);
            })
            ->when((!empty($filter['stype']) || strlen($filter['stype']) > 0), function ($query) use ($filter) {
                return $query->where("dm.type", intval($filter['stype']));
            })
            ->where(["dm.is_delete" => 2])
//            ->orderBy("dm.date", "desc")
            ->orderBy("dm.id", "desc")
            ->paginate($pageSize, ["dm.*", "s.title as supplier_title", "s.store_time"], null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);

        foreach ($res['items'] as $k => &$v) {
            $v['product_amount'] = MenuProductMapping::from("menu_product_mapping as mpm")
                ->join("product as p", "p.id", "=", "mpm.product_id")
                ->where([
                    'p.status' => 1,
                    'mpm.status' => 1,
                    'mpm.menu_id' => $v['id']
                ])
                ->count("mpm.id");

            if (isset($v['store_time']))
                $v['store_time'] = json_decode($v['store_time'], true);
        }
        return $res;
    }

    public function getOne($id = null)
    {
        $res = DailyMenu::query()->where("id", $id)->first();
        if ($res['menu_type'] == 0) {
            $res['expire_date'] = [$res['expire_start_date'], $res['expire_end_date']];
        }
        return $res;
    }

    public function saveOrUpdate($data = [], $id = 0)
    {
        if (!empty($data['id']))
            unset($data['id']);

        if (intval($id)) {
            DailyMenu::where("id", $id)->update($data);
            return $id;
        } else {
            $res = DailyMenu::create($data);
            return $res['id'] ?? "";
        }
    }

    /**
     * 删除
     * @param null $id
     */
    public function deleteDailyMenu($id = null)
    {
        if (!intval($id))
            return retFail("参数错误");

        DailyMenu::where(['id' => intval($id)])->update([
            'is_delete' => 1,
            'deleted_at' => date("Y-m-d H:i:s")
        ]);

        return retSuc([], "删除成功");
    }

    public function delMenuProduct($id = 0)
    {

        if (!intval($id))
            return retFail("参数错误");

        MenuProductMapping::query()->where("id", $id)->update([
            'status' => 0
        ]);

        //查找菜单编号
        $menu_id = MenuProductMapping::query()->where("id", $id)->value("menu_id");
        if ($menu_id) {
            delRedis("menuCateList_" . $menu_id);
        }

        return retSuc([], "删除成功");
    }

    /**
     * 菜单对应的产品
     * @param int $id
     */
    public function getMenuProducts($id = 0)
    {
        if (empty($id))
            return [];

        $res = MenuProductMapping::from("menu_product_mapping as mpm")
            ->join("product_category as pc", "pc.id", "=", "mpm.category_id")
            ->where(['mpm.status' => 1, 'mpm.menu_id' => $id])
//            ->orderBy("mpm.sort", "asc")
            ->orderBy("pc.sort", "asc")
            ->orderBy("mpm.id", "asc")
            ->groupBy("mpm.category_id")
            ->get(['mpm.category_id', 'pc.title', "mpm.menu_id"]);

        if (!isset($res))
            return [];

        foreach ($res as $k => &$v) {
            $v['products'] = MenuProductMapping::from("menu_product_mapping as mpm")
                ->join("product as p", "p.id", "=", "mpm.product_id")
                ->where([
                    'mpm.status' => 1,
                    'mpm.type' => 0,
                    'mpm.menu_id' => $id,
                    'p.status' => 1,
                    'p.is_delete' => 2,
                    'p.category_id' => $v['category_id']
                ])
                ->whereNull("p.deleted_at")
                ->orderBy("mpm.sort", "asc")
                ->orderBy("p.sort", "asc")
                ->get(['mpm.id', 'p.title', 'p.thumb', 'p.price']);
        }

        $combos = MenuProductMapping::from("menu_product_mapping as mp")
            ->join("product_combo as c", "c.id", "=", "mp.product_id")
            ->where([
                'mp.type' => 1,
                'mp.menu_id' => $id,
                'c.status' => 1,
                'mp.status' => 1
            ])
            ->groupBy("mp.product_id")
            ->orderBy('mp.sort', "asc")
            ->get(['mp.id', 'c.title', 'c.price']);

        //套餐
        if (!empty($combos) && count($combos) > 0) {
            $menus[count($res)] = [
                'title' => "套餐/称量菜",
                'products' => $combos
            ];
        }

        return $res;
    }

    /**
     * 复制菜单
     * @param int $menu_id
     */
    public function copyDailyMneu(int $menu_id)
    {
        $menu = $this->getOne($menu_id);
        if (empty($menu))
            return retFail("菜单不存在");

        if ($menu['menu_type'] != 1) {
            return retFail("单店不支持复制菜单");
        }

        $data = $menu->toArray();
        unset($data['id']);
        unset($data['id']);

        $data['status'] = 0;
        $data['start_time'] = date("Y-m-d", strtotime("+1 day")) . ' ' . date("H:i:s", strtotime($menu['start_time']));
        $data['end_time'] = date("Y-m-d", strtotime("+1 day")) . ' ' . date("H:i:s", strtotime($menu['end_time']));
        $data['create_time'] = $date['update_time'] = date("Y-m-d H:i:s");

        if (isset($menu['deliver_time'])) {
            $data['deliver_time'] = date("Y-m-d H:i:s", strtotime("+1 day", strtotime($menu['deliver_time'])));
        }

        $data['date'] = date("Y-m-d", strtotime("+1 day"));
        $res = DailyMenu::create($data);
        if ($res) {
            $mappings = MenuProductMapping::query()
                ->where(['menu_id' => $menu['id'], 'status' => 1])
                ->get(["id", "category_id", "product_id", "type"]);

            $m_data = [];
            foreach ($mappings as $k => $v) {
                $m_data[] = [
                    'category_id' => $v['category_id'],
                    'product_id' => $v['product_id'],
                    'menu_id' => $res['id'],
                    'type' => $v['type'],
                    'update_time' => time(),
                    'create_time' => time(),
                ];
            }

            if (isset($m_data)) {
                MenuProductMapping::insert($m_data);
            }
        }

        return retSuc(['id' => $res['id'] ?? null]);
    }

    /**
     * 获取菜单
     * @param $filter
     */
    public function getOptions($filter = [])
    {
        if (empty($filter))
            return null;

        $res = DailyMenu::query()
            ->when(!empty($filter['shop_id']), function ($q) use ($filter) {
                return $q->where("shop_id", intval($filter['shop_id']));
            })
            ->when(!empty($filter['between']), function ($q) use ($filter) {
                foreach ($filter['between'] as $k => $v) {
                    $q->whereBetween($k, $v);
                }
            })
            ->orderBy("date", "desc")
            ->get(['id', 'date', 'type'])
            ->toArray();

        foreach ($res as $k => &$v) {
            $v['title'] = $v['date'] . ' ' . menu_type($v['type']);
        }

        return $res;
    }

    /**
     * 排序
     * @param int $menu_id
     * @param array $productIds
     */
    public function sortMenuProducts(int $menu_id = 0, $productIds = [])
    {
        if (!$menu_id)
            return retFail("参数错误");

        if (empty($productIds))
            return retFail("参数错误");

        $sql = "";
        $sequence = 10;
        foreach ($productIds as $k => $productId) {
            $sequence += 5;
            $sql = "update wx_menu_product_mapping set `sort`={$sequence} where id={$productId} and menu_id={$menu_id};";

            if ($sql) {
                DB::update(DB::raw($sql));
            }
        }

        delRedis("menuCateList_" . $menu_id);

        return retSuc([], "排序成功");
    }

}
